package huffman;

import java.util.ArrayList;
import java.util.Collections;

public class HuffmanTreeDemo {
    public static void main(String[] args) {
        HuffmanTree huffmanTree = new HuffmanTree(new int[] { 13, 7, 8, 3, 29, 6, 1 });
        Node root = huffmanTree.create();
        root.preOrder();
    }
}

class HuffmanTree {
    private int[] arr;

    HuffmanTree(int[] arr) {
        this.arr = arr;
    }

    public Node create() {
        // 将每个数构造成一个Node，并放入ArrayList中
        ArrayList<Node> nodes = new ArrayList<Node>();
        for (int i : arr) {
            nodes.add(new Node(i));
        }
        // 不断构造
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            // 取出最小的两个二叉树构建新的二叉树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            // 删除两个节点，并加入新的节点
            nodes.remove(0);
            nodes.remove(0);
            nodes.add(parent);
        }
        return nodes.get(0);
    }

    public void preOrder(Node root) {
        root.preOrder();
    }
}

// 为了让Node对象支持排序，实现comparable接口
class Node implements Comparable<Node> {
    public int value;
    public Node left;
    public Node right;

    Node(int v) {
        this.value = v;
    }

    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    @Override
    public String toString() {
        return "Node[" + value + "]";
    }

    @Override
    public int compareTo(Node o) {
        // 从小到大排序
        return this.value - o.value;
    }
}